package hzst.android.form.view;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import hzst.android.R;
import hzst.android.adapter.CommonAdapter;
import hzst.android.entity.Accessory;
import hzst.android.util.AFinalUtil;
import hzst.android.util.FileUtil;
import hzst.android.util.L;
import hzst.android.util.MediaUtil;
import hzst.android.util.SysIntentUtil;
import hzst.android.view.ListViewForScrollView;
/**
 * 附件选择控件。
 * 展示附件列表，点击打开附件；选择添加附件(图库、照相机)；保存附件信息，用于后续上传、删除等操作。
 * @author wt
 *
 */
public class FMAccessoryView extends LinearLayout{

	private List<Accessory> accessoryList = new ArrayList<>();
	private List<Accessory> netAccessories = new ArrayList<>();
	private List<Accessory> localAccessories = new ArrayList<>();
	private LinearLayout llayOptions;
	private TextView tvChoose;
	private TextView tvCamera;
	private ListViewForScrollView lvAccessory;

	private Dialog dialogOperation;
	private CommonAdapter<Accessory> adapter;
	private Context context;

	private boolean choiceEnable = true;
	private boolean enable = true;
	private String savePath;
	private OnTakePhotoListener onTakePhotoListener;
	private OnAccessoryDeleteListener onAccessoryDeleteListener;

	private static final int TYPE_NET = 1;
	private static final int TYPE_LOCAL = 2;

	public FMAccessoryView(Context context) {
		super(context);
		this.context = context;
		initView();
		initEvents();
	}
	public FMAccessoryView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		initView();
		initEvents();
	}
	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}
	public List<String> getUploadAccessories(){
		List<String> list = new ArrayList<>();
		for (Accessory accessory : localAccessories) {
			if(!accessory.isUploaded()){
				list.add(accessory.getAttachmentUrl());
			}
		}
		return list;
	}
	public boolean isEnable() {
		return enable;
	}
	public void setEnable(boolean enable) {
		this.enable = enable;
		if(enable){
			llayOptions.setVisibility(View.VISIBLE);
//			lvAccessory.setEnabled(true);
		}else{
			llayOptions.setVisibility(View.GONE);
//			lvAccessory.setEnabled(false);
		}
	}
	public boolean isChoiceEnable() {
		return choiceEnable;
	}
	public void setChoiceEnable(boolean choiceEnable) {
		this.choiceEnable = choiceEnable;
		if(choiceEnable){
			llayOptions.setVisibility(View.VISIBLE);
		}else{
			llayOptions.setVisibility(View.GONE);
		}
	}
	public OnTakePhotoListener getOnTakePhotoListener() {
		return onTakePhotoListener;
	}
	public void setOnTakePhotoListener(OnTakePhotoListener onTakePhotoListener) {
		this.onTakePhotoListener = onTakePhotoListener;
	}

	public OnAccessoryDeleteListener getOnAccessoryDeleteListener() {
		return onAccessoryDeleteListener;
	}
	public void setOnAccessoryDeleteListener(
			OnAccessoryDeleteListener onAccessoryDeleteListener) {
		this.onAccessoryDeleteListener = onAccessoryDeleteListener;
	}
	public List<Accessory> getAccessoryList() {
		return accessoryList;
	}
	public void setAccessoryList(List<Accessory> accessoryList) {
		this.accessoryList = accessoryList;
	}
	public List<Accessory> getNetAccessories() {
		return netAccessories;
	}
	public void setNetAccessories(List<Accessory> netAccessories) {
		if(this.netAccessories.size() > 0){
			for (int i = 0; i < this.netAccessories.size(); i++) {
				accessoryList.remove(i);
			}
			for (int i = 0; i < netAccessories.size(); i++) {
				accessoryList.set(i, netAccessories.get(i));
			}
		}else{
			accessoryList.addAll(netAccessories);
		}
		this.netAccessories = netAccessories;
		refreshList();
	}
	public List<Accessory> getLocalAccessories() {
		return localAccessories;
	}
//	public void setLocalAccessories(List<String> localAccessories) {
//		this.localAccessories = localAccessories;
//	}
	private void initView(){
		View view = LayoutInflater.from(context) .inflate(R.layout.view_accessory, this);
		llayOptions = (LinearLayout) view.findViewById(R.id.llay_options);
		lvAccessory = (ListViewForScrollView) view.findViewById(R.id.lv_accessory);
		tvChoose = (TextView) view.findViewById(R.id.tv_choose);
		tvCamera = (TextView) view.findViewById(R.id.tv_camera);

	}
	private void initEvents(){
		tvChoose.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				SysIntentUtil intentUtil = new SysIntentUtil(context);
				intentUtil.openFileManager();
			}
		});

		tvCamera.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				SysIntentUtil intentUtil = new SysIntentUtil(context);
				intentUtil.takePhoto();
			}
		});

		lvAccessory.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				if(position >= netAccessories.size() && enable){
					createOperationDialog(position,TYPE_LOCAL);
				}else{
					createOperationDialog(position,TYPE_NET);
				}
				dialogOperation.show();
				return true;
			}
		});
		lvAccessory.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if(position >= netAccessories.size()){
					FileUtil fileUtils = new FileUtil(context);
					fileUtils.openFile(new File(accessoryList.get(position).getAttachmentUrl()));
				}else{
					AFinalUtil aFinalHelper = new AFinalUtil(context);
					String filePath = netAccessories.get(position).getAttachmentUrl();
					try {
						aFinalHelper.openNetRes(filePath, savePath+filePath.substring(filePath.lastIndexOf("/") + 1));
					} catch (NullPointerException e) {
						L.showLogInfo(L.TAG_EXCEPTION, "请设置附件保存路径setSavePath");
					}
				}
			}
		});
	}

	private void createOperationDialog(final int position,final int type){
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setItems(new String[]{"删除"}, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (type) {
				case TYPE_NET:
					if(onAccessoryDeleteListener != null){
						onAccessoryDeleteListener.deleteNetAccessory(netAccessories.get(position));
					}
					break;
				case TYPE_LOCAL:
					accessoryList.remove(position);
					localAccessories.remove(position - netAccessories.size());
					refreshList();
					break;
				}

			}
		});
		dialogOperation = builder.create();
	}
	/**
	 * 添加附件，由页面主动调用
	 * @param uri
	 */
	public void addAccessory(Uri uri){
		String path = MediaUtil.getPath(context, uri);

		accessoryList.add(new Accessory(path));
		localAccessories.add(new Accessory(path));
		refreshList();
	}
	public void addAccessory(String filePath){
		accessoryList.add(new Accessory(filePath));
		localAccessories.add(new Accessory(filePath));
		refreshList();
	}
//	public void addAccessory(List<String> pathList){
//		accessoryList.addAll(pathList);
//		refreshList();
//	}
	/**
	 * 附件是否重复
	 */
	public boolean isRepeated(String filePath){
		for (Accessory accessory : localAccessories) {
			if(accessory.getAttachmentUrl().equals(filePath)){
				Toast.makeText(context, "已经有这个文件了", Toast.LENGTH_SHORT).show();
				return true;
			}
		}
		return true;
	}
	public void uploadCompleted(){
		for (Accessory accessory : localAccessories) {
			accessory.setUploaded(true);
		}
	}
	public void deleteNetAccessory(Accessory accessory){
		netAccessories.remove(accessory);
		accessoryList.remove(accessory);
		refreshList();
	}
	public void refreshList(){
		if(adapter == null){
			adapter = new CommonAdapter<Accessory>(context, accessoryList, R.layout.adapter_accessory) {

				@Override
				public void convert(ViewHolder helper, Accessory item, int position) {
					helper.setText(R.id.tv_accessory, "[附件"+(position + 1)+"]："+item.getAttachmentName());
				}

			};
			lvAccessory.setAdapter(adapter);
		}else{
			adapter.setData(accessoryList);
			adapter.notifyDataSetChanged();
		}
//		setListViewHeightBasedOnChildren(lvAccessory);
//		lvAccessory.setSelection(lvAccessory.getChildCount() - 1);
	}

	public void setListViewHeightBasedOnChildren(ListView listView) {

		// 获取ListView对应的Adapter
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}
		int totalHeight = 0;
		for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
			// listAdapter.getCount()返回数据项的数目
			View listItem = listAdapter.getView(i, null, listView);
			// 计算子项View 的宽高
			listItem.measure(0, 0);
			// 统计所有子项的总高度
			totalHeight += listItem.getMeasuredHeight();
		}
			ViewGroup.LayoutParams params = listView.getLayoutParams();
			params.height = totalHeight+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
			params.width = lvAccessory.getWidth();
			// listView.getDividerHeight()获取子项间分隔符占用的高度
			// params.height最后得到整个ListView完整显示需要的高度
			listView.setLayoutParams(params);
	}
	@Deprecated
	public interface OnTakePhotoListener{
		File createFile();
	}
	public interface OnAccessoryDeleteListener{
		void deleteNetAccessory(Accessory accessory);
	}
}
